package LinkedList;

public class _61_RotateList {
    public ListNode rotateRight(ListNode head, int k) {
            ListNode cur = head;
            int N = 0;
            while(cur!=null){
                cur = cur.next;
                N++;
            }
            if(N==0 || N==1 ||k==0) return head;
            if(k>=N){
                k = k%N;
            }
            cur = head;
            int count = 1;
            ListNode beginNode = null;
            while(cur!=null){
                if(count==N){
                    cur.next = head;
                }
                if(count==N-k) {
                    ListNode temp = cur.next;
                    cur.next = null;
                    cur = temp;
                }else if(count==N-k+1){
                    beginNode = cur;
                    cur = cur.next;
                }else{
                    cur = cur.next;
                }
                count++;
            }
            return beginNode;
    }
}
